package servlet;

import service.WxService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @ClassName servlet.WxServlet
 * @Author wuyuyang
 * @Date 2022/1/12 15:15
 * @Description servlet.WxServlet
 * @Version 1.0
 */
@WebServlet("/wx")
public class WxServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        System.out.println("get");

        /**
         *  signature  微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
         timestamp  时间戳
         nonce	     随机数
         echostr	     随机字符串
         */
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        System.out.println(signature);
        System.out.println(timestamp);
        System.out.println(nonce);
        System.out.println(echostr);
        // 校验签名
        if (WxService.check(timestamp, nonce, signature)) {
            System.out.println("接入成功！");
            PrintWriter out = response.getWriter();
            // 原样返回echostr参数
            out.print(echostr);
            out.flush();
            out.close();
        } else {
            System.out.println("接入失败！");
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        Map<String,String> map = WxService.parseRequest(req.getInputStream());
//        System.out.println(map);//关注测试号,给测试公众号发消息,就可以看到打印结果了

//        //设置编码格式,不然中文会乱码
//        req.setCharacterEncoding("UTF-8");
//        resp.setCharacterEncoding("UTF-8");
//        //将请求中的xml参数转成map
//        Map<String,String> map = WxService.parseRequest(req.getInputStream());
//        System.out.println(map);
//        //回复消息
//        String textMsg = "<xml><ToUserName><![CDATA["+map.get("FromUserName")+"]]></ToUserName><FromUserName><![CDATA["+map.get("ToUserName")+"]]></FromUserName><CreateTime>12345678</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[hello]]></Content></xml>";
//        resp.getWriter().print(textMsg);

        //设置编码格式,不然中文会乱码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        //将请求中的xml参数转成map
        Map<String,String> map = WxService.parseRequest(req.getInputStream());
        System.out.println(map);
        //处理完将响应一个xml给微信
        String respXml = WxService.getRespose(map);
        System.out.println(respXml);
        resp.getWriter().print(respXml);
    }
}
